<!-- //#region Template -->
<template>
  <div class="bom-details-page">
    <el-card class="summary-card" shadow="never">
      <div class="summary-header">
        <div>
          <div class="page-title">BOM详情</div>

        </div>
        <div class="action-group">
          <el-button type="primary" @click="Backway()">返回列表</el-button>
        </div>
      </div>
      <!-- 操作日志 -->
      <div class="meta-line">
        <el-space wrap>
          <span>最后操作人：{{ Nloginfo.createname || '—' }}</span>
          <span>最后操作时间：{{ formatLogTime(Nloginfo.createtime) }}</span>
        </el-space>
      </div>
    </el-card>
    <el-row :gutter="16" class="content-row">
      <el-col :xs="24" :lg="16">
        <el-card shadow="never" class="info-card">
          <el-tabs v-model="activeTab" class="info-tabs">
            <el-tab-pane label="BOM信息" name="info">
              <section class="section">
                <div class="section-title">基础信息</div>
                <el-descriptions :column="2" border :label-class-name="'desc-label'"
                  :content-class-name="'desc-content'" size="small">
                  <el-descriptions-item label="BOM编号">{{ BOMDetails.itemcode }}</el-descriptions-item>
                  <el-descriptions-item label="BOM主题">{{ BOMDetails.goodsname }}</el-descriptions-item>
                  <el-descriptions-item label="是否启用">{{ BOMDetails.isUse == true ? "启用" : "禁用" }}</el-descriptions-item>
                  <el-descriptions-item label="类别">{{ BOMDetails.category }}</el-descriptions-item>
                  <el-descriptions-item label="规格">{{ BOMDetails.spec }}</el-descriptions-item>
                  <el-descriptions-item label="版本">{{ BOMDetails.version }}</el-descriptions-item>
                  <el-descriptions-item label="备注" :span="2">
                    {{ BOMDetails.remark || '—' }}
                  </el-descriptions-item>
                </el-descriptions>
              </section>
            </el-tab-pane>
            <el-tab-pane label="BOM配件" name="parts">
              <section class="section">
                <div class="section-title">配件清单</div>
                <el-form :model="partsQueryParams" label-width="90px" @submit.prevent class="parts-search-form">
                  <el-row :gutter="16">
                    <el-col :xs="24" :sm="12" :md="8" :lg="6">
                      <el-form-item label="物料名称">
                        <el-input v-model="partsQueryParams.GoodsName" placeholder="请输入物料名称" clearable />
                      </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="8" :lg="6">
                      <el-form-item label="物品编号">
                        <el-input v-model="partsQueryParams.Itemcode" placeholder="请输入物品编号" clearable />
                      </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="8" :lg="6">
                      <el-form-item label="分类">
                        <el-select v-model="partsQueryParams.Category" placeholder="请选择分类" clearable>
                          <el-option label="成品" value="成品" />
                          <el-option label="半成品" value="半成品" />
                          <el-option label="原材料" value="原材料" />
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row justify="end" :gutter="12">
                    <el-col :xs="24" :sm="12" :md="8" :lg="6" class="search-actions">
                      <el-space wrap>
                        <el-button type="primary" @click="handlePartsSearch">查询</el-button>
                        <el-button @click="handlePartsReset">重置</el-button>
                        <el-button type="success" @click="openSemiProductDialog()">添加半成品</el-button>                      
                      </el-space>
                    </el-col>
                  </el-row>
                </el-form>
                <div class="table-container">
                  <el-table :data="partsList" border size="small" style="width: 100%" v-loading="partsLoading">
                    <el-table-column type="selection" width="50" align="center" fixed="left" />
                    <el-table-column type="index" label="序号" width="60" align="center" fixed="left" />
                    <el-table-column prop="itemcode" label="物品编号" min-width="120" show-overflow-tooltip />
                    <el-table-column prop="goodsname" label="物料名称" min-width="140" show-overflow-tooltip />
                    <el-table-column prop="spec" label="规格" min-width="120" show-overflow-tooltip />
                    <el-table-column prop="unit" label="单位" width="80" align="center" />
                    <el-table-column prop="category" label="类别" width="100" align="center" />
                    <el-table-column prop="version" label="版本" width="80" align="center" />
                    <el-table-column prop="number" label="数量" width="100" align="right" />
                    <el-table-column prop="isUse" label="是否使用" width="100" align="center">
                      <template #default="{ row }">
                        <el-tag :type="row.isUse ? 'success' : 'info'" size="small">
                          {{ row.isUse ? '是' : '否' }}
                        </el-tag>
                      </template>
                    </el-table-column>
                    <el-table-column prop="remark" label="备注" min-width="120" show-overflow-tooltip />
                    <el-table-column label="操作" width="300" fixed="right" align="center">
                      <template #default="{ row }">
                        <el-space spacer="|" size="small">
                          <el-button type="success" link size="small" @click="openRawMaterialDialog(row)">添加原料</el-button>          
                          <el-button type="primary" link size="small" @click="openEditDialog(row)">编辑</el-button>
                          <el-button type="danger" link size="small" @click="handleDeleteBOM(row)">删除</el-button>
                        </el-space>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
                <div class="structure-footer">
                  <el-pagination v-model:current-page="partsPage.Pageindex" v-model:page-size="partsPage.Pagesize"
                    :page-sizes="[10, 20, 30, 50]" layout="total, sizes, prev, pager, next"
                    :total="partsPage.Totalcount" @size-change="handlePartsSizeChange"
                    @current-change="handlePartsPageChange" />
                </div>
              </section>
            </el-tab-pane>

            <el-tab-pane label="工艺流程" name="process">
              <section class="section">
                <div class="section-title">工艺流程管理</div>
                <div class="process-toolbar">
                  <el-space>
                    <el-button type="primary" @click="handleAddProcess">添加</el-button>
                    <el-button type="danger" @click="handleRemoveSelectedProcess" :disabled="selectedProcessRows.length === 0">移除</el-button>
                    <el-button type="success" @click="handleSaveProcessFlow" :loading="processFlowSaving">保存</el-button>
                  </el-space>
                </div>
                <div class="table-container">
                  <el-table :data="flatProcessFlowList" border size="small" style="width: 100%" row-key="tempId" 
                    height="580" 
                    v-loading="processFlowLoading"
                    @selection-change="handleProcessSelectionChange">
                    <el-table-column type="selection" width="50" align="center" />
                    <el-table-column type="index" label="序号" width="60" align="center" />
                    <el-table-column prop="processcode" label="工序编码" min-width="120" align="center">
                      <template #default="{ row, $index }">
                        <el-input v-model="row.processcode" size="small" placeholder="请输入工序编码" />
                      </template>
                    </el-table-column>
                    <el-table-column prop="processname" label="工序名称" min-width="180" align="center">
                      <template #default="{ row }">
                        <el-input v-model="row.processname" size="small" placeholder="请输入工序名称" />
                      </template>
                    </el-table-column>
                    <el-table-column prop="kahuna" label="负责人" width="120" align="center">
                      <template #default="{ row }">
                        <el-input v-model="row.kahuna" size="small" placeholder="请输入负责人" />
                      </template>
                    </el-table-column>
                    <el-table-column prop="departmentname" label="所属部门" width="140" align="center">
                      <template #default="{ row }">
                        <el-input v-model="row.departmentname" size="small" placeholder="请输入部门" />
                      </template>
                    </el-table-column>
                    <el-table-column prop="remark" label="备注" min-width="200" align="center">
                      <template #default="{ row }">
                        <el-input v-model="row.remark" size="small" placeholder="请输入备注" />
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="180" fixed="right" align="center">
                      <template #default="{ row, $index }">
                        <el-space spacer="|" size="small">
                          <el-button type="primary" link size="small" @click="handleMoveUp($index)" :disabled="$index === 0">上移</el-button>
                          <el-button type="primary" link size="small" @click="handleMoveDown($index)" :disabled="$index === flatProcessFlowList.length - 1">下移</el-button>
                          <el-button type="danger" link size="small" @click="handleRemoveProcess($index)">移除</el-button>
                        </el-space>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
                <div class="structure-footer">
                  <span style="color: #909399; font-size: 12px;">
                    共 {{ flatProcessFlowList.length }} 条记录
                  </span>
                </div>
              </section>
            </el-tab-pane>

            <el-tab-pane label="操作记录" name="logs">
              <section class="section">
                <div class="section-title">操作记录</div>
                <div class="logs-toolbar">
                  <el-button @click="handleExportLogs">导出</el-button>
                  <el-input v-model="logsQueryParams.SearchKeyword" placeholder="请搜索" clearable style="width: 300px"
                    @keyup.enter="handleLogsSearch">
                    <template #prefix>
                      <el-icon>
                        <Search />
                      </el-icon>
                    </template>
                  </el-input>
                </div>
                <el-table :data="logsList" border size="small" style="width: 100%" v-loading="logsLoading">
                  <el-table-column type="selection" width="50" align="center" />
                  <el-table-column type="index" label="序号" width="60" align="center" />
                  <el-table-column prop="createname" label="操作人" width="120" align="center" show-overflow-tooltip />
                  <el-table-column prop="kind" label="操作类型" width="100" align="center">
                    <template #default="{ row }">
                      <el-tag :type="getLogKindType(row.kind)" size="small">
                        {{ row.kind || '—' }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="createtime" label="操作时间" width="180" align="center">
                    <template #default="{ row }">
                      {{ moment(row.createtime).format("yyyy-MM-DD HH:mm:ss") }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="message" label="操作内容" min-width="200" show-overflow-tooltip />
                </el-table>
                <div class="structure-footer">
                  <el-pagination v-model:current-page="logsPage.Pageindex" v-model:page-size="logsPage.Pagesize"
                    :page-sizes="[5, 10, 20, 30, 50]" layout="total, sizes, prev, pager, next"
                    :total="logsPage.Totalcount" @size-change="handleLogsSizeChange"
                    @current-change="handleLogsPageChange" />
                </div>
              </section>
            </el-tab-pane>
            <!-- BOM结构 -->
          </el-tabs>
        </el-card>
      </el-col>
      <el-col :xs="24" :lg="8">
        <el-card shadow="never" class="structure-card">
          <div class="structure-header">
            <div class="structure-title">BOM结构展开</div>
            <el-button link @click="toggleAll">
              {{ isAllExpanded ? '全部折叠' : '全部展开' }}
            </el-button>
          </div>
          <el-table :data="displayBOM" border size="small" row-key="id" :default-expand-all="isAllExpanded"
            :tree-props="{ children: 'children' }" height="580" v-loading="treeLoading">
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="itemcode" label="物品编号" min-width="120" show-overflow-tooltip />
            <el-table-column prop="goodsname" label="物料名称" min-width="140" show-overflow-tooltip />
            <el-table-column prop="category" label="分类" width="100" align="center">
              <template #default="{ row }">
                <el-tag :type="row.category === '成品' ? 'success' : row.category === '半成品' ? 'warning' : 'info'" size="small">
                  {{ row.category || '—' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="spec" label="规格" min-width="120" show-overflow-tooltip />
            <el-table-column prop="version" label="版本" width="80" />
            <el-table-column prop="unit" label="单位" width="80" />
            <el-table-column prop="isUse" label="是否使用" width="100" align="center">
              <template #default="{ row }">
                <el-tag :type="row.isUse ? 'success' : 'info'" size="small">
                  {{ row.isUse ? '是' : '否' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="number" label="配件数量" width="100" align="right" />
            <el-table-column prop="remark" label="备注" min-width="120" show-overflow-tooltip />
            <el-table-column label="操作" width="100" fixed="right" align="center">
              <template #default="{ row }">
                <el-button type="danger" link size="small" @click="handleDeleteBOM(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="structure-footer">
            <el-pagination small layout="total, prev, pager, next" :total="displayBOM.length"
              :page-size="displayBOM.length" :current-page="1" disabled />
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-dialog v-model="childDialogVisible" title="创建子BOM" width="640px" :close-on-click-modal="false">
      <el-form ref="childFormRef" :model="childForm" :rules="childFormRules" label-width="100px">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="父级节点" prop="parentid">
              <el-select v-model="childForm.parentid" placeholder="请选择父级" @change="handleParentChange">
                <el-option v-for="item in parentOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="子级ID">
              <el-input v-model="childForm.childrenId" placeholder="保存后自动生成" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="物品编号" prop="itemcode">
              <el-input v-model="childForm.itemcode" placeholder="请输入物品编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料名称" prop="goodsname">
              <el-input v-model="childForm.goodsname" placeholder="请输入物料名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="规格型号" prop="spec">
              <el-input v-model="childForm.spec" placeholder="请输入规格" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="childForm.unit" placeholder="请输入单位" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="分类" prop="category">
              <el-select v-model="childForm.category" placeholder="请选择分类">
                <el-option label="成品" value="成品" />
                <el-option label="半成品" value="半成品" />
                <el-option label="原材料" value="原材料" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="版本" prop="version">
              <el-input v-model="childForm.version" placeholder="默认版本" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="配件数量" prop="number">
              <el-input-number v-model="childForm.number" :min="1" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否使用" prop="isUse">
              <el-switch v-model="childForm.isUse" active-text="启用" inactive-text="停用" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="childForm.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="childDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="childSubmitting" @click="handleChildSubmit">保存</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="editDialogVisible" title="编辑BOM配件" width="640px" :close-on-click-modal="false">
      <el-form ref="editFormRef" :model="editForm" :rules="editFormRules" label-width="100px">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="父级ID">
              <el-input v-model="editForm.parentid" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="子级ID">
              <el-input v-model="editForm.childrenId" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="版本">
              <el-input v-model="editForm.version" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="物品编号" prop="itemcode">
              <el-input v-model="editForm.itemcode" placeholder="请输入物品编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料名称" prop="goodsname">
              <el-input v-model="editForm.goodsname" placeholder="请输入物料名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="规格型号" prop="spec">
              <el-input v-model="editForm.spec" placeholder="请输入规格" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="editForm.unit" placeholder="请输入单位" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="分类" prop="category">
              <el-select v-model="editForm.category" placeholder="请选择分类">
                <el-option label="成品" value="成品" />
                <el-option label="半成品" value="半成品" />
                <el-option label="原材料" value="原材料" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="配件数量" prop="number">
              <el-input-number v-model="editForm.number" :min="1" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="是否使用" prop="isUse">
              <el-switch v-model="editForm.isUse" active-text="启用" inactive-text="停用" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="editForm.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="editSubmitting" @click="handleEditSubmit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<!-- //#endregion Template -->

<script setup lang="ts">
//#region Imports
import { computed, onMounted, reactive, ref, watch } from 'vue'
import myaxios from '@/Http/http'
import moment from 'moment'
import { useRoute } from 'vue-router'
import router from '@/router'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { useCounterStore } from '@/stores/counter'
//#endregion

const route = useRoute();
// 获取Pinia store中的用户信息
const counterStore = useCounterStore();
const getQueryString = (value: unknown) => typeof value === 'string' ? value : ''
const routeId = getQueryString(route.query.id)
const routeItemcode = getQueryString(route.query.itemcode)
const routeVersion = getQueryString(route.query.version)
const routeChildrenId = getQueryString(route.query.childrenId)
onMounted(() => {
  GetBOMDetails(); // 先获取详情，详情获取成功后再获取其他数据
  GetBOMLogs(); // 操作记录不依赖详情数据，可以立即获取
});

//#region  单条日志

// 接受日志的变量
const Nloginfo = reactive({
  createtime: '',
  createname: '',
  updatetime: '',
  updatename: ''
})
const resetNloginfo = () => {
  Nloginfo.createtime = ''
  Nloginfo.createname = ''
  Nloginfo.updatetime = ''
  Nloginfo.updatename = ''
}
const formatLogTime = (value?: string | Date | null) => {
  if (!value) {
    return '—'
  }
  const formatted = moment(value)
  return formatted.isValid() ? formatted.format('yyyy-MM-DD HH:mm:ss') : '—'
}
// 成品操作日志获取
const GetNloginfo = () => {
  if (!BOMDetails.id) {
    resetNloginfo()
    return
  }
  myaxios.get("/api/BOMs/BOMfinishedNlog", {
    params: {
      Id: BOMDetails.id
    }
  }).then(res => {
    if (res.data && res.data.code === 200 && res.data.result) {
      Object.assign(Nloginfo, res.data.result)
    } else {
      resetNloginfo()
      ElMessage.info(res.data?.message || '暂未查询到最后操作记录')
    }
  }).catch(err => {
    console.error('获取最后操作记录失败:', err)
    resetNloginfo()
    ElMessage.error('获取最后操作记录失败')
  })
}

//#endregion

//#region  Bom成品详情变量

const BOMDetails = reactive({  //Bom成品详情变量
  "id": routeId,
  "itemcode": routeItemcode,
  "goodsname": "",
  "spec": "",
  "unit": "",
  "category": "",
  "version": routeVersion,
  "number": 1,
  "remark": "",
  "isUse": false,
  "parentid": null,
  "childrenId": routeChildrenId || '',
  "isDel": false,
  "children": null
})
//成品操作日志获取
const GetBOMDetails = () => {
  if (!BOMDetails.id) {
    console.warn('BOM ID为空，无法获取详情')
    return
  }
  myaxios.get("/api/BOMs/GetBOMDetails", {
    params: {
      Id: BOMDetails.id
    }
  }).then(res => {
    if (res.data && res.data.result) {
      Object.assign(BOMDetails, res.data.result)
      syncParentContext()
      // 详情获取成功后，再获取树形结构和配件列表
      GetTreeway()
      GetBOMPartsList()
      GetNloginfo() // 日志也需要详情ID
      // 如果当前在工艺流程标签页，自动加载工艺流程数据
      if (activeTab.value === 'process') {
        GetProcessFlowTree()
      }
    }
  }).catch(err => {
    console.error('获取BOM详情失败:', err)
  })
}

//#endregion

//#region  树形结构展示
interface TreeNode {
  id: number | string | null
  itemcode: string
  goodsname: string
  spec: string
  unit: string
  category: string
  version: string
  number: number | null
  remark: string
  isUse: boolean
  parentid: string | null
  isDel: boolean
  childrenId?: string
  children?: TreeNode[]
}
const TreeData = ref<TreeNode[]>([])
const treeLoading = ref(false)
// 获取BOM树形结构（根据当前成品ID隔离数据）
const GetTreeway = () => {
  // 确保有有效的ID或ChildrenId
  if (!BOMDetails.id && !BOMDetails.childrenId) {
    console.warn('BOM ID和ChildrenId都为空，无法获取树形结构')
    TreeData.value = []
    return
  }
  
  console.log('获取BOM树形结构，成品ID:', BOMDetails.id, 'ChildrenId:', BOMDetails.childrenId, 'Version:', BOMDetails.version);
  const params: any = {}
  
  // 如果有效品ID，传递ProductId用于数据隔离
  if (BOMDetails.id) {
    params.ProductId = BOMDetails.id
  }
  
  // 如果有效品ChildrenId，使用它作为根节点；否则使用'F0'
  if (BOMDetails.childrenId) {
    params.RootParentId = BOMDetails.childrenId
  } else {
    params.RootParentId = 'F0'
  }
  
  // 如果有效品版本，传递Version用于版本查询（从详情返回值获取，无需显示）
  if (BOMDetails.version) {
    params.Version = BOMDetails.version
  }
  
  treeLoading.value = true
  myaxios.get("/api/BOMs/GetBOMTree", { params })
    .then(res => {
      console.log('BOM树形结构数据:', res.data);
      if (res.data && res.data.code === 200) {
        TreeData.value = res.data.result || []
      } else {
        console.warn('获取BOM树形结构失败:', res.data?.message || '未知错误')
        TreeData.value = []
        ElMessage.warning(res.data?.message || '获取BOM树形结构失败')
      }
    })
    .catch(err => {
      console.error('获取BOM树形结构失败:', err);
      TreeData.value = []
      ElMessage.error('获取BOM树形结构失败')
    })
    .finally(() => {
      treeLoading.value = false
    })
}
const displayBOM = computed(() => TreeData.value)
const flattenTreeNodes = computed<TreeNode[]>(() => {
  const result: TreeNode[] = []
  const traverse = (nodes: TreeNode[]) => {
    nodes?.forEach(item => {
      result.push(item)
      if (item.children?.length) {
        traverse(item.children)
      }
    })
  }
  traverse(TreeData.value)
  return result
})
const parentOptions = computed(() => {
  const options = flattenTreeNodes.value
    .filter(node => node.childrenId)
    .map(node => ({
      label: `${node.goodsname || node.itemcode || node.childrenId}`,
      value: node.childrenId as string
    }))
  return [
    {
      label: `${BOMDetails.goodsname || '根节点'}（成品）`,
      value: 'F0'
    },
    ...options
  ]
})
const isAllExpanded = ref(true)
const activeTab = ref('info')
const toggleAll = () => {
  isAllExpanded.value = !isAllExpanded.value
}
const currentParentId = ref(routeChildrenId || 'F0')
const childDialogVisible = ref(false)
const childFormRef = ref<FormInstance>()
const defaultVersion = computed(() => BOMDetails.version || '1.0V')
const childForm = reactive({
  parentid: currentParentId.value,
  childrenId: '',
  itemcode: '',
  goodsname: '',
  spec: '',
  unit: '',
  category: '',
  version: defaultVersion.value,
  number: 1,
  remark: '',
  isUse: true
})
watch(defaultVersion, (val) => {
  if (!childDialogVisible.value) {
    childForm.version = val
  }
})
const childFormRules = reactive<FormRules>({
  parentid: [{ required: true, message: '请选择父级', trigger: 'change' }],
  itemcode: [{ required: true, message: '请输入物品编号', trigger: 'blur' }],
  goodsname: [{ required: true, message: '请输入物料名称', trigger: 'blur' }],
  spec: [{ required: true, message: '请输入规格', trigger: 'blur' }],
  unit: [{ required: true, message: '请输入单位', trigger: 'blur' }],
  category: [{ required: true, message: '请选择分类', trigger: 'change' }],
  number: [{ required: true, message: '请输入数量', trigger: 'change' }]
})
const resetChildForm = () => {
  childForm.parentid = currentParentId.value
  childForm.childrenId = ''
  childForm.itemcode = ''
  childForm.goodsname = ''
  childForm.spec = ''
  childForm.unit = ''
  childForm.category = ''
  childForm.version = defaultVersion.value
  childForm.number = 1
  childForm.remark = ''
  childForm.isUse = true
}
// 打开添加半成品对话框（表格外，直接添加到当前成品下）
const openSemiProductDialog = () => {
  // 半成品直接添加到当前成品下，使用当前成品的childrenId作为parentid
  childForm.parentid = BOMDetails.childrenId || 'F0'
  childForm.itemcode = ''
  childForm.goodsname = ''
  childForm.spec = ''
  childForm.unit = ''
  childForm.category = '半成品'  // 固定为半成品
  childForm.number = 1
  childForm.remark = ''
  handleParentChange()
  childDialogVisible.value = true
}

// 打开添加原料对话框（表格内，添加到选中行的子级）
const openRawMaterialDialog = (row?: any) => {
  if (!row) {
    ElMessage.warning('请先选择一行数据')
    return
  }
  // 原料添加到选中行的子级，使用选中行的childrenId作为parentid
  if (row.childrenId) {
    childForm.parentid = row.childrenId
  } else {
    ElMessage.warning('选中的行没有子级ID，无法添加原料')
    return
  }
  childForm.itemcode = ''
  childForm.goodsname = ''
  childForm.spec = ''
  childForm.unit = ''
  childForm.category = '原材料'  // 固定为原材料
  childForm.number = 1
  childForm.remark = ''
  handleParentChange()
  childDialogVisible.value = true
}

const openChildDialog = (row?: any) => {
  if (row?.childrenId) {
    childForm.parentid = row.childrenId
  } else if (row?.parentid) {
    childForm.parentid = row.parentid
  } else {
    childForm.parentid = BOMDetails.childrenId || 'F0'
  }
  childForm.itemcode = ''
  childForm.goodsname = ''
  childForm.spec = ''
  childForm.unit = ''
  childForm.category = ''
  childForm.number = 1
  childForm.remark = ''
  handleParentChange()
  childDialogVisible.value = true
}
const handleParentChange = () => {
  const parentNode = flattenTreeNodes.value.find(item => item.childrenId === childForm.parentid)
  childForm.version = parentNode?.version || defaultVersion.value
}
const childSubmitting = ref(false)
const editDialogVisible = ref(false)
const editSubmitting = ref(false)
const editFormRef = ref<FormInstance>()
const editForm = reactive({
  id: '',
  parentid: '',
  childrenId: '',
  version: '',
  itemcode: '',
  goodsname: '',
  spec: '',
  unit: '',
  category: '',
  number: 1,
  remark: '',
  isUse: true
})
const editFormRules = reactive<FormRules>({
  itemcode: [{ required: true, message: '请输入物品编号', trigger: 'blur' }],
  goodsname: [{ required: true, message: '请输入物料名称', trigger: 'blur' }],
  spec: [{ required: true, message: '请输入规格', trigger: 'blur' }],
  unit: [{ required: true, message: '请输入单位', trigger: 'blur' }],
  category: [{ required: true, message: '请选择分类', trigger: 'change' }],
  number: [{ required: true, message: '请输入数量', trigger: 'change' }]
})
const resetEditForm = () => {
  editForm.id = ''
  editForm.parentid = ''
  editForm.childrenId = ''
  editForm.version = ''
  editForm.itemcode = ''
  editForm.goodsname = ''
  editForm.spec = ''
  editForm.unit = ''
  editForm.category = ''
  editForm.number = 1
  editForm.remark = ''
  editForm.isUse = true
}
const handleChildSubmit = () => {
  if (!childFormRef.value) return
  childFormRef.value.validate(async (valid) => {
    if (!valid) return
    childSubmitting.value = true
    try {
      // 从Pinia store获取当前登录人真实姓名，优先使用realname，如果为空则使用username
      const currentUserName = counterStore.userinfo.realname || counterStore.userinfo.username || ''
      console.log('创建子级BOM - 当前登录人信息:', {
        realname: counterStore.userinfo.realname,
        username: counterStore.userinfo.username,
        currentUserName: currentUserName
      })
      const payload = {
        parentid: childForm.parentid,
        itemcode: childForm.itemcode,
        goodsname: childForm.goodsname,
        spec: childForm.spec,
        unit: childForm.unit,
        category: childForm.category,
        version: childForm.version,
        number: childForm.number,
        remark: childForm.remark,
        isUse: childForm.isUse,
        CurrentUserName: currentUserName
      }
      const res = await myaxios.post("/api/BOMs/CreateChildBOM", payload)
      if (res.data && res.data.code === 200) {
        const newNode = res.data.result
        childForm.childrenId = newNode?.childrenId || ''
        const successMsg = newNode?.childrenId ? `子级BOM创建成功（ID: ${newNode.childrenId}）` : '子级BOM创建成功'
        ElMessage.success(successMsg)
        childDialogVisible.value = false
        GetTreeway()
        GetBOMPartsList()
      } else {
        ElMessage.error(res.data?.message || '子级BOM创建失败')
      }
    } catch (error) {
      console.error('创建子级BOM失败', error)
      ElMessage.error('创建子级BOM失败')
    } finally {
      childSubmitting.value = false
    }
  })
}
const openEditDialog = (row: any) => {
  if (!row) return
  editForm.id = row.id
  editForm.parentid = row.parentid || ''
  editForm.childrenId = row.childrenId || ''
  editForm.version = row.version || defaultVersion.value
  editForm.itemcode = row.itemcode || ''
  editForm.goodsname = row.goodsname || ''
  editForm.spec = row.spec || ''
  editForm.unit = row.unit || ''
  editForm.category = row.category || ''
  editForm.number = row.number || 1
  editForm.remark = row.remark || ''
  editForm.isUse = row.isUse ?? true
  editDialogVisible.value = true
}
const handleEditSubmit = () => {
  if (!editFormRef.value) return
  editFormRef.value.validate(async (valid) => {
    if (!valid) return
    editSubmitting.value = true
    try {
      // 从Pinia store获取当前登录人真实姓名，优先使用realname，如果为空则使用username
      const currentUserName = counterStore.userinfo.realname || counterStore.userinfo.username || ''
      console.log('更新子级BOM - 当前登录人信息:', {
        realname: counterStore.userinfo.realname,
        username: counterStore.userinfo.username,
        currentUserName: currentUserName
      })
      const payload = {
        Id: editForm.id,
        Itemcode: editForm.itemcode,
        Goodsname: editForm.goodsname,
        Spec: editForm.spec,
        Unit: editForm.unit,
        Category: editForm.category,
        Number: editForm.number,
        Remark: editForm.remark,
        IsUse: editForm.isUse,
        CurrentUserName: currentUserName
      }
      const res = await myaxios.put("/api/BOMs/UpdateChildBOM", payload)
      if (res.data && res.data.code === 200) {
        ElMessage.success('BOM配件已更新')
        editDialogVisible.value = false
        GetTreeway()
        GetBOMPartsList()
      } else {
        ElMessage.error(res.data?.message || 'BOM配件更新失败')
      }
    } catch (error) {
      console.error('更新BOM配件失败', error)
      ElMessage.error('BOM配件更新失败')
    } finally {
      editSubmitting.value = false
    }
  })
}
watch(childDialogVisible, (val) => {
  if (!val) {
    childFormRef.value?.clearValidate()
    resetChildForm()
  }
})
watch(editDialogVisible, (val) => {
  if (!val) {
    editFormRef.value?.clearValidate()
    resetEditForm()
  }
})

//#endregion

//#region  BOM配件列表

// BOM配件查询参数
const partsQueryParams = reactive({
  Pageindex: 1,
  Pagesize: 20,
  GoodsName: '',
  Itemcode: '',
  Category: '',
  Parentid: currentParentId.value
})

const syncParentContext = () => {
  currentParentId.value = BOMDetails.childrenId || routeChildrenId || 'F0'
  partsQueryParams.Parentid = currentParentId.value
  if (!childDialogVisible.value) {
    childForm.parentid = currentParentId.value
  }
}
syncParentContext()

// BOM配件分页信息
const partsPage = reactive({
  Pageindex: 1,
  Pagesize: 20,
  Totalcount: 0
})

// BOM配件列表数据
const partsList = ref<any[]>([])

// BOM配件加载状态
const partsLoading = ref(false)

// 获取BOM配件列表
const GetBOMPartsList = () => {
  if (!partsQueryParams.Parentid) {
    return
  }
  partsLoading.value = true
  myaxios.get("/api/BOMs/GetBOMList", {
    params: {
      Pageindex: partsQueryParams.Pageindex,
      Pagesize: partsQueryParams.Pagesize,
      GoodsName: partsQueryParams.GoodsName || undefined,
      Itemcode: partsQueryParams.Itemcode || undefined,
      Category: partsQueryParams.Category || undefined,
      Parentid: partsQueryParams.Parentid || undefined
    }
  }).then(res => {
    console.log(res.data)
    if (res.data && res.data.listResult) {
      partsList.value = res.data.listResult
      partsPage.Totalcount = res.data.totalcount || 0
    } else {
      partsList.value = []
      partsPage.Totalcount = 0
    }
  }).catch(err => {
    console.error('获取BOM配件列表失败:', err)
    partsList.value = []
    partsPage.Totalcount = 0
  }).finally(() => {
    partsLoading.value = false
  })
}

// 分页大小改变事件
const handlePartsSizeChange = (val: number) => {
  partsQueryParams.Pagesize = val
  partsPage.Pagesize = val
  partsQueryParams.Pageindex = 1
  partsPage.Pageindex = 1
}

// 当前页改变事件
const handlePartsPageChange = (val: number) => {
  partsQueryParams.Pageindex = val
  partsPage.Pageindex = val
}

// 查询事件
const handlePartsSearch = () => {
  const oldPageIndex = partsPage.Pageindex
  partsQueryParams.Pageindex = 1
  partsPage.Pageindex = 1
  // 如果页码已经是1，watch不会触发，需要手动调用
  if (oldPageIndex === 1) {
    GetBOMPartsList()
  }
}

// 重置事件
const handlePartsReset = () => {
  const oldPageIndex = partsPage.Pageindex
  partsQueryParams.GoodsName = ''
  partsQueryParams.Itemcode = ''
  partsQueryParams.Category = ''
  partsQueryParams.Pageindex = 1
  partsPage.Pageindex = 1
  // 如果页码已经是1，watch不会触发，需要手动调用
  if (oldPageIndex === 1) {
    GetBOMPartsList()
  }
}

// 监听分页变化，自动加载数据
watch(
  () => [partsPage.Pageindex, partsPage.Pagesize],
  () => {
    partsQueryParams.Pageindex = partsPage.Pageindex
    partsQueryParams.Pagesize = partsPage.Pagesize
    GetBOMPartsList()
  }
)

//#endregion

//#region  BOM操作记录

// BOM操作记录查询参数
const logsQueryParams = reactive({
  Pageindex: 1,
  Pagesize: 10,
  SearchKeyword: ''
})

// BOM操作记录分页信息
const logsPage = reactive({
  Pageindex: 1,
  Pagesize: 10,
  Totalcount: 0
})

// BOM操作记录列表数据
const logsList = ref<any[]>([])

// BOM操作记录加载状态
const logsLoading = ref(false)

// 获取BOM操作记录列表（无需外键参数，获取所有BOM相关操作日志）
const GetBOMLogs = () => {
  logsLoading.value = true
  myaxios.get("/api/BOMs/GetBOMLogs", {
    params: {
      Pageindex: logsQueryParams.Pageindex,
      Pagesize: logsQueryParams.Pagesize,
      SearchKeyword: logsQueryParams.SearchKeyword || undefined
    }
  }).then(res => {
    console.log('BOM操作记录:', res.data)
    if (res.data && res.data.listResult) {
      logsList.value = res.data.listResult
      logsPage.Totalcount = res.data.totalcount || 0
    } else {
      logsList.value = []
      logsPage.Totalcount = 0
    }
  }).catch(err => {
    console.error('获取BOM操作记录失败:', err)
    logsList.value = []
    logsPage.Totalcount = 0
  }).finally(() => {
    logsLoading.value = false
  })
}

// 分页大小改变事件
const handleLogsSizeChange = (val: number) => {
  logsQueryParams.Pagesize = val
  logsPage.Pagesize = val
  logsQueryParams.Pageindex = 1
  logsPage.Pageindex = 1
}

// 当前页改变事件
const handleLogsPageChange = (val: number) => {
  logsQueryParams.Pageindex = val
  logsPage.Pageindex = val
}

// 搜索事件
const handleLogsSearch = () => {
  const oldPageIndex = logsPage.Pageindex
  logsQueryParams.Pageindex = 1
  logsPage.Pageindex = 1
  // 如果页码已经是1，watch不会触发，需要手动调用
  if (oldPageIndex === 1) {
    GetBOMLogs()
  }
}

// 导出操作记录
const handleExportLogs = () => {
  ElMessage.info('导出功能待实现')
  // TODO: 实现导出功能
}

// 获取日志操作类型的标签类型（用于显示不同颜色的标签）
const getLogKindType = (kind: string | undefined): string => {
  if (!kind) return 'info'
  const kindLower = kind.toLowerCase()
  if (kindLower.includes('新增') || kindLower.includes('添加') || kindLower.includes('创建')) {
    return 'success'
  } else if (kindLower.includes('修改') || kindLower.includes('更新')) {
    return 'warning'
  } else if (kindLower.includes('删除') || kindLower.includes('移除')) {
    return 'danger'
  } else if (kindLower.includes('启用') || kindLower.includes('激活')) {
    return 'success'
  } else if (kindLower.includes('禁用') || kindLower.includes('停用')) {
    return 'info'
  }
  return 'info'
}

// 监听分页变化，自动加载数据
watch(
  () => [logsPage.Pageindex, logsPage.Pagesize],
  () => {
    logsQueryParams.Pageindex = logsPage.Pageindex
    logsQueryParams.Pagesize = logsPage.Pagesize
    GetBOMLogs()
  }
)

// 监听标签页切换，切换到操作记录时自动加载
watch(
  () => activeTab.value,
  (newTab) => {
    if (newTab === 'logs') {
      GetBOMLogs()
    } else if (newTab === 'process') {
      // 切换到工艺流程标签页时，自动加载工艺流程数据
      GetProcessFlowTree()
    }
  }
)

//#endregion

//#region  工艺流程管理

// 工艺流程树形结构接口定义
interface ProcessFlowTreeNode {
  id: number | string
  processname: string
  processcode: string
  processdescription: string
  version: string
  goodsname: string
  deliverables: string
  kahuna: string
  departmentname: string
  isUse: boolean
  spanTime: number
  equipmentId: number
  parentid: number
  children?: ProcessFlowTreeNode[]
}

// 工艺流程编辑列表项接口定义（扁平列表，用于编辑）
interface ProcessFlowEditItem {
  tempId: string | number // 临时ID，用于编辑时标识
  id?: number | string // 原始ID（如果有）
  processname: string
  processcode: string
  processdescription?: string
  version: string
  goodsname: string
  deliverables?: string
  kahuna: string
  departmentname: string
  isUse: boolean
  spanTime: number
  equipmentId: number
  parentid: number
  remark?: string // 备注字段
  sortOrder: number // 排序顺序
}

// 工艺流程原始树形数据（只读，用于加载）
const processFlowList = ref<ProcessFlowTreeNode[]>([])

// 工艺流程扁平编辑列表数据（可编辑）
const flatProcessFlowList = ref<ProcessFlowEditItem[]>([])

// 工艺流程加载状态
const processFlowLoading = ref(false)

// 工艺流程保存状态
const processFlowSaving = ref(false)

// 工艺流程展开状态（已废弃，保留避免报错）
const isProcessFlowExpanded = ref(true)

// 选中的工序行
const selectedProcessRows = ref<ProcessFlowEditItem[]>([])

// 将树形结构扁平化为列表（递归函数）
// 遍历树形结构，将所有节点（包括子节点）扁平化为列表
const flattenTreeToList = (nodes: ProcessFlowTreeNode[], parentid: number = 0, sortOrder: number = 0): ProcessFlowEditItem[] => {
  const result: ProcessFlowEditItem[] = []
  let currentSortOrder = sortOrder
  
  nodes?.forEach(node => {
    // 将树节点转换为编辑项
    const editItem: ProcessFlowEditItem = {
      tempId: `temp_${Date.now()}_${Math.random()}`, // 生成临时ID
      id: node.id, // 保留原始ID
      processname: node.processname || '',
      processcode: node.processcode || '',
      processdescription: node.processdescription || '',
      version: node.version || BOMDetails.version || 'V1.0',
      goodsname: node.goodsname || BOMDetails.goodsname || '',
      deliverables: node.deliverables || '',
      kahuna: node.kahuna || '',
      departmentname: node.departmentname || '',
      isUse: node.isUse ?? true,
      spanTime: node.spanTime || 0,
      equipmentId: node.equipmentId || 1,
      parentid: parentid,
      remark: '', // 备注字段，默认为空
      sortOrder: currentSortOrder++
    }
    result.push(editItem)
    
    // 递归处理子节点（不再递归，只处理根节点）
    // 如果需要包含子节点，取消下面的注释
    // if (node.children && node.children.length > 0) {
    //   const children = flattenTreeToList(node.children, Number(node.id), currentSortOrder)
    //   result.push(...children)
    //   currentSortOrder += children.length
    // }
  })
  
  return result
}

// 获取工艺流程树形结构
// 根据BOM详情的成品名称和版本查询工艺流程树形结构，然后扁平化为列表
const GetProcessFlowTree = () => {
  // 验证必填参数：产品名称和版本
  if (!BOMDetails.goodsname || !BOMDetails.version) {
    console.log(BOMDetails)
    console.warn('产品名称或版本为空，无法获取工艺流程数据')
    processFlowList.value = []
    flatProcessFlowList.value = []
    return
  }

  processFlowLoading.value = true
  myaxios.get("/api/Makesteps/GetMakestepTree", {
    params: {
      Goodsname: BOMDetails.goodsname,
      Version: BOMDetails.version
    }
  }).then(res => {
    console.log('工艺流程树形结构数据:', res.data)
    if (res.data && res.data.code === 200) {
      const result = res.data.result || []
      // 确保每个节点都有children属性（即使为空数组），并确保数据类型正确
      const normalizeTree = (nodes: ProcessFlowTreeNode[]): ProcessFlowTreeNode[] => {
        if (!nodes || nodes.length === 0) {
          return []
        }
        return nodes.map(node => ({
          ...node,
          id: Number(node.id) || 0,
          parentid: Number(node.parentid) || 0,
          spanTime: Number(node.spanTime) || 0,
          equipmentId: Number(node.equipmentId) || 0,
          isUse: Boolean(node.isUse),
          children: node.children && node.children.length > 0 ? normalizeTree(node.children) : []
        }))
      }
      processFlowList.value = normalizeTree(result)
      
      // 将树形结构扁平化为列表（只取根节点）
      flatProcessFlowList.value = flattenTreeToList(result, 0, 0)
      
      // 更新排序顺序
      flatProcessFlowList.value.forEach((item, index) => {
        item.sortOrder = index + 1
      })
      
      if (result.length === 0) {
        ElMessage.info('暂无工艺流程数据')
      } else {
        console.log('工艺流程数据加载成功，共', flatProcessFlowList.value.length, '条记录')
      }
    } else {
      console.warn('获取工艺流程树形结构失败:', res.data?.message || '未知错误')
      processFlowList.value = []
      flatProcessFlowList.value = []
      ElMessage.warning(res.data?.message || '获取工艺流程树形结构失败')
    }
  }).catch(err => {
    console.error('获取工艺流程树形结构失败:', err)
    processFlowList.value = []
    flatProcessFlowList.value = []
    ElMessage.error('获取工艺流程树形结构失败')
  }).finally(() => {
    processFlowLoading.value = false
  })
}

// 添加工序
// 在列表末尾添加一个新的工序项
const handleAddProcess = () => {
  const newItem: ProcessFlowEditItem = {
    tempId: `temp_${Date.now()}_${Math.random()}`,
    processname: '',
    processcode: '',
    processdescription: '',
    version: BOMDetails.version || 'V1.0',
    goodsname: BOMDetails.goodsname || '',
    deliverables: '',
    kahuna: '',
    departmentname: '',
    isUse: true,
    spanTime: 0,
    equipmentId: 1,
    parentid: 0,
    remark: '',
    sortOrder: flatProcessFlowList.value.length + 1
  }
  flatProcessFlowList.value.push(newItem)
  ElMessage.success('已添加工序，请填写信息')
}

// 移除选中的工序
// 移除表格中选中的工序行
const handleRemoveSelectedProcess = () => {
  if (selectedProcessRows.value.length === 0) {
    ElMessage.warning('请先选择要移除的工序')
    return
  }
  
  ElMessageBox.confirm(
    `确定要移除选中的 ${selectedProcessRows.value.length} 条工序吗？`,
    '确认移除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 获取选中行的临时ID
    const selectedIds = selectedProcessRows.value.map(row => row.tempId)
    // 移除选中的行
    flatProcessFlowList.value = flatProcessFlowList.value.filter(item => !selectedIds.includes(item.tempId))
    // 更新排序顺序
    flatProcessFlowList.value.forEach((item, index) => {
      item.sortOrder = index + 1
    })
    selectedProcessRows.value = []
    ElMessage.success('已移除选中的工序')
  }).catch(() => {
    // 用户取消操作
  })
}

// 移除指定索引的工序
// 移除表格中指定索引的工序行
const handleRemoveProcess = (index: number) => {
  const item = flatProcessFlowList.value[index]
  if (!item) {
    ElMessage.warning('工序不存在')
    return
  }
  
  ElMessageBox.confirm(
    `确定要移除工序"${item.processname || item.processcode || '未命名'}"吗？`,
    '确认移除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    flatProcessFlowList.value.splice(index, 1)
    // 更新排序顺序
    flatProcessFlowList.value.forEach((item, idx) => {
      if (item) {
        item.sortOrder = idx + 1
      }
    })
    ElMessage.success('已移除工序')
  }).catch(() => {
    // 用户取消操作
  })
}

// 上移工序
// 将指定索引的工序向上移动一位
const handleMoveUp = (index: number) => {
  if (index <= 0) {
    ElMessage.warning('已经是第一条，无法上移')
    return
  }
  
  const currentItem = flatProcessFlowList.value[index]
  const prevItem = flatProcessFlowList.value[index - 1]
  
  if (!currentItem || !prevItem) {
    ElMessage.warning('工序不存在，无法移动')
    return
  }
  
  // 交换位置（使用数组方法确保类型安全）
  const newList = [...flatProcessFlowList.value]
  newList[index] = prevItem
  newList[index - 1] = currentItem
  flatProcessFlowList.value = newList
  
  // 更新排序顺序
  flatProcessFlowList.value.forEach((item, idx) => {
    if (item) {
      item.sortOrder = idx + 1
    }
  })
  
  ElMessage.success('已上移')
}

// 下移工序
// 将指定索引的工序向下移动一位
const handleMoveDown = (index: number) => {
  if (index >= flatProcessFlowList.value.length - 1) {
    ElMessage.warning('已经是最后一条，无法下移')
    return
  }
  
  const currentItem = flatProcessFlowList.value[index]
  const nextItem = flatProcessFlowList.value[index + 1]
  
  if (!currentItem || !nextItem) {
    ElMessage.warning('工序不存在，无法移动')
    return
  }
  
  // 交换位置（使用数组方法确保类型安全）
  const newList = [...flatProcessFlowList.value]
  newList[index] = nextItem
  newList[index + 1] = currentItem
  flatProcessFlowList.value = newList
  
  // 更新排序顺序
  flatProcessFlowList.value.forEach((item, idx) => {
    if (item) {
      item.sortOrder = idx + 1
    }
  })
  
  ElMessage.success('已下移')
}

// 处理表格选中变化
// 当表格选中项发生变化时更新selectedProcessRows
const handleProcessSelectionChange = (selection: ProcessFlowEditItem[]) => {
  selectedProcessRows.value = selection
}

// 保存工艺流程
// 清除旧的工艺流程，保存新的工艺流程列表
const handleSaveProcessFlow = async () => {
  // 验证必填参数
  if (!BOMDetails.goodsname || !BOMDetails.version) {
    ElMessage.error('产品名称或版本为空，无法保存工艺流程')
    return
  }
  
  // 验证工序数据
  if (flatProcessFlowList.value.length === 0) {
    ElMessage.warning('没有工序数据，无法保存')
    return
  }
  
  // 验证必填字段
  for (let i = 0; i < flatProcessFlowList.value.length; i++) {
    const item = flatProcessFlowList.value[i]
    if (!item || !item.processcode || !item.processname) {
      ElMessage.error(`第 ${i + 1} 条工序的工序编码或工序名称不能为空`)
      return
    }
  }
  
  processFlowSaving.value = true
  try {
    // 从Pinia store获取当前登录人真实姓名
    const currentUserName = counterStore.userinfo.realname || counterStore.userinfo.username || ''
    
    // 准备保存数据：将扁平列表转换为保存格式
    const saveData = {
      Goodsname: BOMDetails.goodsname,
      Version: BOMDetails.version,
      CurrentUserName: currentUserName,
      ProcessSteps: flatProcessFlowList.value.map((item, index) => ({
        Id: item.id || 0, // 如果是新添加的，ID为0
        Processname: item.processname,
        Processcode: item.processcode,
        Processdescription: item.processdescription || '',
        Version: item.version,
        Goodsname: item.goodsname,
        Deliverables: item.deliverables || '',
        Kahuna: item.kahuna || '',
        Departmentname: item.departmentname || '',
        IsUse: item.isUse,
        SpanTime: item.spanTime || 0,
        EquipmentId: item.equipmentId || 1,
        Parentid: 0, // 扁平列表，所有工序的父级ID为0
        SortOrder: item.sortOrder || index + 1,
        Remark: item.remark || ''
      }))
    }
    
    console.log('保存工艺流程数据:', saveData)
    
    const res = await myaxios.post("/api/Makesteps/SaveMakestepList", saveData)
    
    if (res.data && res.data.code === 200) {
      ElMessage.success('工艺流程保存成功')
      // 保存成功后，重新加载数据
      GetProcessFlowTree()
    } else {
      ElMessage.error(res.data?.message || '工艺流程保存失败')
    }
  } catch (err: any) {
    console.error('保存工艺流程失败:', err)
    ElMessage.error(err.response?.data?.message || '工艺流程保存失败')
  } finally {
    processFlowSaving.value = false
  }
}

// 切换工艺流程展开/折叠状态（已废弃，保留避免报错）
const toggleProcessFlowExpand = () => {
  isProcessFlowExpanded.value = !isProcessFlowExpanded.value
}

//#endregion

// 软删除BOM
const handleDeleteBOM = (row: any) => {
  ElMessageBox.confirm(
    `确定要删除"${row.goodsname || row.itemcode}"吗？删除后数据将无法恢复。`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      // 从Pinia store获取当前登录人真实姓名
      const currentUserName = counterStore.userinfo.realname || counterStore.userinfo.username || ''
      const res = await myaxios.post('/api/BOMs/DeleteBOM', {
        Id: row.id,
        CurrentUserName: currentUserName
      })
      
      if (res.data && res.data.code === 200) {
        ElMessage.success('删除成功')
        // 刷新树形结构和配件列表
        GetTreeway()
        GetBOMPartsList()
      } else {
        ElMessage.error(res.data?.message || '删除失败')
      }
    } catch (err: any) {
      console.error('删除BOM失败:', err)
      ElMessage.error(err.response?.data?.message || '删除失败')
    }
  }).catch(() => {
    // 用户取消操作
  })
}

const Backway = () => {  //退回到列表
  router.push("/BOMllist")
}


</script>

<!-- //#region Style -->
<style scoped>
.bom-details-page {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 16px;
  background-color: #f5f7fa;
  min-height: 100%;
}

.summary-card {
  border-radius: 8px;
}

.summary-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 16px;
  margin-bottom: 12px;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  color: #1f2329;
  margin-bottom: 6px;
}

.bom-title {
  font-size: 16px;
  font-weight: 500;
  color: #4e5969;
}

.action-group {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.meta-line {
  font-size: 13px;
  color: #86909c;
}

.content-row {
  flex: 1;
}

.info-card,
.structure-card {
  border-radius: 8px;
  min-height: 640px;
}

.info-tabs {
  --el-tabs-header-height: 44px;
}

.section {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.section-title {
  font-size: 15px;
  font-weight: 600;
  color: #1d2129;
}

.desc-label {
  width: 140px;
  background-color: #f5f7fa;
  font-weight: 500;
}

.desc-content {
  color: #4e5969;
}

.stock-panel {
  display: flex;
  flex-direction: column;
  gap: 4px;
  padding: 8px;
  border: 1px solid #e5e6eb;
  border-radius: 4px;
  background-color: #f9fafb;
}

.stock-item {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #86909c;
}

.footer-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.structure-card {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.structure-quick-add {
  padding: 8px 0 4px;
  border-bottom: 1px dashed #e5e6eb;
  margin-bottom: 8px;
}

.structure-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.structure-title {
  font-size: 16px;
  font-weight: 600;
  color: #1d2129;
}

.structure-footer {
  display: flex;
  justify-content: flex-end;
  padding-top: 8px;
}

.parts-search-form {
  margin-bottom: 16px;
  padding: 16px;
  background-color: #fafafa;
  border-radius: 4px;
}

.search-actions {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.table-container {
  width: 100%;
  overflow-x: auto;
}

.table-container :deep(.el-table) {
  min-width: 100%;
}

.table-container :deep(.el-table__body-wrapper) {
  overflow-x: auto;
  overflow-y: auto;
}

/* 工艺流程表格样式优化 - 数据居中显示 */
.table-container :deep(.el-table td.el-table__cell) {
  text-align: center;
}

.table-container :deep(.el-table th.el-table__cell) {
  background-color: #f5f7fa;
  font-weight: 600;
  text-align: center;
}

/* 树形表格展开图标样式 */
.table-container :deep(.el-table__expand-icon) {
  color: #409eff;
}

.logs-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 12px;
  background-color: #fafafa;
  border-radius: 4px;
}

.process-toolbar {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 16px;
  padding: 12px;
  background-color: #fafafa;
  border-radius: 4px;
}
</style>
<!-- //#endregion Style -->
